<?php
namespace app\api\controller;
/*积分控制器*/

use think\facade\Db;
use think\Request;
use app\BaseController;
use app\common\controller\ApiController;
use think\App;

class Integral extends ApiController
{

    public function initialize()
    {
        parent::initialize();
        $this->model = app('app\common\model\mall\IntegralItem');
        $this->order = app('app\common\model\mall\IntegralOrder');
        $this->item_sku = app('app\common\model\mall\IntegralItemSku');
        $this->integral_detail = app('app\common\model\user\IntegralDetail');
        $this->user = app('app\common\model\user\WxUsers');


    }

    /*
 * 
 * 积分商品列表
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
    public function index(Request $request){
        $model = $this->model;
        if($request->param('name')){
            $model = $model->where('title','like','%'.$request->param('name').'%');
        }
        // $info = $this->user->find($request->user_id);
        $res = $model->where('status',1)->order('create_time','desc')
            ->paginate($request->param('limit',10));
        $data = [
            'total'     => $res->total(),         // 总记录数
            'current_page'       => $res->currentPage(),   // 当前页码
            'per_page'      => $res->listRows(),      // 每页记录数
            'data'      => $res->items()          // 分页数据
        ];
        if($request->user_id ){
            $info = $this->user->find($request->user_id);
            $data['integral']=$info->integral;
        } else{
            $data['integral']=0;
        }

        return json(['code'=>200,'msg'=>'获取成功','data'=>$data]);
    }

    /**
     * Show the form for editing the specified resource.
     * 商品详情
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function item_detail(Request $request)
    {
        //验证用户信息
        /* $userInfo= $this->user->where('openid',$request->only('openid'))->get();
 
         if(!$userInfo){
             return json(['code'=>202,'msg'=>'用户信息异常']);
         };*/

        $info = $this->model->with('sku')->find($request->param('id'))->toArray();


        if(!$info){
            return json(['code'=>202,'msg'=>'帖子不存在']);
        };
        $info['images'] = array_filter($info['image']);
        $address = app('app\common\model\system\Configuration')->withoutGlobalScope()->find(21);


        return json(['code'=>200,'msg'=>'返回成功','data'=>['address'=>$address->val,'info'=>$info]]);

    }


    /*
     *
     * Show the form for editing the specified resource.
     * 提交订单
     * @param  int  $id
     * @return \Illuminate\Http\Response
    */
    public function create_order(Request $request)
    {
        $data = $request->param();

        //验证用户信息
        $userInfo= $this->user->find($request->user_id);
        $data['user_id'] = $request->user_id;
        if(!$userInfo){
            return json(['code'=>202,'msg'=>'用户信息异常']);
        };

        $prefix = date('Ymd');
        //检查
        try{
            Db::startTrans(); //开启事务

            if(!$data['sku_id'] || !$this->model->where('id',$data['goods_id'])->find() || !$this->item_sku->where('id',$data['sku_id'])->find()){
                return json(['code'=>202,'msg'=>'此商品或规格不存在']);
            }


            //如果没有传规格id

            $info = $this->model->find($data['goods_id']);
            $sku_info = $this->item_sku->find($data['sku_id']);
            $data['order_sn'] = $prefix.random_int(100000, 999999).$prefix;
            $data['sku_name'] = $sku_info->attribute;
            $data['amount'] = $sku_info->attr_price;

            if($data['number']*$data['amount'] > $userInfo->integral){
                return json(['code'=>202,'msg'=>'积分不足']);

            }

            //扣除库存

            $this->item_sku->where('id',$data['sku_id'])->dec('number',$data['number'])->update();
            $this->model->where('id',$data['goods_id'])->dec('inventory',$data['number'])->update();
            //增加销量
            $this->model->where('id',$data['goods_id'])->inc('sale',$data['number'])->update();
            //扣除积分
            $this->user->where('id',$data['user_id'])->dec('integral',$data['amount'])->update();
            /*dump($this->user->where('id',$data['user_id'])->find());
            dd($this->user->getLastSql());*/
            //生成积分明细
            $this->integral_detail->save(['user_id'=>$request->user_id ,'description'=>'积分兑换商品','integral'=>$data['amount'],'type'=>0]);

            $this->order->save($data);
            Db::Commit();
            return json(['code'=>200,'msg'=>'生成成功']);
        }catch (\Exception $exception){
            Db::Rollback();
            return json(['code'=>202,'msg'=>'生成失败','data'=>$exception->getMessage()]);
        }

    }


    /*
     *
     * Show the form for editing the specified resource.
     * 订单列表
     * @param  int  $id
     * @return \Illuminate\Http\Response
    */
    public function order(Request $request){
        $model = $this->order;

        $res = $model->where(['user_id'=>$request->user_id,'status'=>$request->param('status',0)])->with('goods')->order('create_time','desc')
            ->paginate($request->param('limit',10));
        $data = [
            'total'     => $res->total(),         // 总记录数
            'current_page'       => $res->currentPage(),   // 当前页码
            'per_page'      => $res->listRows(),      // 每页记录数
            'data'      => $res->items()          // 分页数据
        ];
        return json(['code'=>200,'msg'=>'获取成功','data'=>$data]);
    }

}